package com.model.demo.designmodel.template.jdbc;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class JdbdTemplate {

    private DataSource dataSource;

    public JdbdTemplate(DataSource dataSource){
        this.dataSource=dataSource;
    }

    //1.获取连接
    //2.准备语句集
    //3.执行语句集
    //4.处理结果集
    //5.关闭结果集
    //6.关闭语句集
    //7.关闭连接
    public List<?> excuteQuery(String sql, RowMapper<?> rowMapper, Object[] value){
        try {
            Connection con=this.getConnection();
            PreparedStatement ps=this.createPrepareStatement(con,sql);
            ResultSet rs=this.excuteQuery(ps, value);
            List<?> prepareResultSet=this.prepareResultSet(rs, rowMapper);
            this.closeResultSet(rs);
            this.closePrepareStatememnt(ps);
            this.closeConnection(con);
            return prepareResultSet;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return null;
    }

    protected void closeResultSet(ResultSet rs) throws Exception {
        rs.close();
    }

    protected void closePrepareStatememnt(PreparedStatement ps) throws Exception {
        ps.close();
    }

    protected void closeConnection(Connection con) throws Exception {
        con.close();
    }

    protected List<?> prepareResultSet(ResultSet rs, RowMapper<?> rowMapper) throws Exception {
        List<Object> resultList=new ArrayList<>();
        int rowNum = 1;
        while(rs.next()){
            Object o = rowMapper.mapRow(rs, rowNum++);
            resultList.add(o);
        }
        return resultList;
    }

    protected ResultSet excuteQuery(PreparedStatement ps, Object[] value) throws Exception {
        for (int i = 0; i < value.length ; i++) {
            ps.setObject(i, value[i]);

        }
        return ps.executeQuery();
    }

    protected PreparedStatement createPrepareStatement(Connection con, String sql)throws Exception {
          return con.prepareStatement(sql);
    }


    protected Connection getConnection() throws Exception {
        return this.dataSource.getConnection();
    }

    


}
